<?php
/*!
 * LostKids PHP Library v0.1 
 * http://huali.li/
 *
 * Copyright 2011, 
 * Written By James Pang
 *  
 * Date: 2011/2/14
 */

class RegisterImpl implements Register
{
    private $recognizer;
    private $adaptor;
    protected $dm;

    public function __construct() {
    	$this->recognizer = Assembly::getService('Recognizer', true);
        $this->adaptor = Assembly::getService('MsgSrcAdaptor', true);
        $this->dm = Assembly::getService('DataManager', true);
    }

    public function registerFaces($msg)
    {
        if(!($msg instanceof BatchMessage))
            $msg = new BatchMessage($msg);
        try{
            $recoged = $this->recognizer->recognize($msg->imgUrls);
        } catch(BizException $e) {
        	if($e->getMessage() == Recognizer::ERR_MULTI_FACES) {
                $this->replyMsgUpdateStatus($e->getCode(), $msg,
                     ResourceBundle::getMsg(Recognizer::ERR_MULTI_FACES), WeiboMessage::ST_ABORT);
        		return;
        	}
        }

        if(count($recoged) == 0) {// no matchs
            // too few imgs to register new photo
            if(count($msg->ids) < app_minRegisterImg) {
                $this->replyMsgUpdateStatus(null, $msg, ResourceBundle::getMsg(
                        $msg->isSeek() ? Recognizer::ERR_REG_NEED_MORE_IMGS
                        : Recognizer::ERR_NO_MATCH_REPORTER, app_minRegisterImg),
                        WeiboMessage::ST_DONE);
            	return;
            }

            // add new kid
            $this->registerUser($msg);
        } else {
            $this->dm->createMatchPanel($msg->getNormBatchKey(), $recoged);
            // inquire user about match
            $this->inquireMatch($msg, $recoged);
        }
    }

    public function registerUser($msg) {
        $this->matchFaces0($msg, $msg->genUserId());
    }

    public function matchFaces($msg) {
        // user must exist
        if(!$msg->getMatchId() || !$this->isFaceExisting($msg->getMatchId())) {
            $this->replyMsgUpdateStatus(null, $msg, ResourceBundle::getMsg(
            MsgSrcPluginAbs::MSG_ERR_INVALID_MATCHID), null);
            return;
        }

        $this->matchFaces0($msg, $msg->getMatchId());
    }

    public function matchFaces0($msg, $userId) {
        $set = $msg->isSeek() ? Recognizer::SET_SEEKER : Recognizer::SET_REPORTER;
        try{
            $this->recognizer->train($userId, $set, $msg->getOwnerId(), $msg->imgUrls);
        } catch(BizException $e) {
            if($e->getMessage() == Recognizer::ERR_MULTI_FACES) {
                $this->replyMsgUpdateStatus($e->getCode(), $msg,
                     ResourceBundle::getMsg(Recognizer::ERR_MULTI_FACES), WeiboMessage::ST_ABORT);
                return;
            }
        }
        $this->dm->saveUsersMatch($msg->ids, $userId);

        // report new kid registered
        $this->replyMsgUpdateStatus(null, $msg, ResourceBundle::getMsg(
                'newUserRegistered', $userId), WeiboMessage::ST_DONE);
    }

    public function confirmFound($msg, $userId)
    {
        ;
    }

    protected function isFaceExisting($userId) {
        if(!$userId)
            return false;
    	return $this->dm->isUserInFaceDB($userId);
    }

    /**
     * inquire owner to do the match
     */
    protected function inquireMatch($msg, $matchs) {
        var_dump($matchs);
        $this->replyMsgUpdateStatus(null, $msg, ResourceBundle::getMsg('inquireMatch',
                $this->getMaxMatch($matchs)), WeiboMessage::ST_HUNG);

        foreach($matchs as $uid=> $confidence) {
            // TODO get img urls
            $imgUrls = null;
            $this->replyMsgUpdateStatus(null, $msg, ResourceBundle::getMsg(
                    'displayMatch', $uid, $imgUrls));
        }
    }

    private function getMaxMatch($matchs) {
        $ret = null;
        $max = -100;
    	foreach($matchs as $uid => $confidence) {
    		if($confidence > $max) {
                $max = $confidence;
    			$ret = $uid;
    		}
    	}
        return $ret;
    }

    /**
     * @param string $lid, msg local id
     */
    protected function replyMsgUpdateStatus($lid, $msg, $text, $newMsgStatus = null) {
        if(!$lid)
            $msg = $this->dm->getMsg($lid);
        $this->adaptor->replyMsg($msg, $text, true);
        if($newMsgStatus)
            $this->dm->updateMsgsStatus($msg, $newMsgStatus);
    }
}
?>
